/*报警图标*/
var alarmIcon = "<span class='alarm-Icon'>报警</span>";
var faultIcon = "<span class='fault-Icon'>故障</span>";
var shellIcon = "<span class='shell-Icon'>屏蔽</span>";
var normalIcon = "<span class='normal-Icon'>正常</span>";
/*火灾高位信号模块列表数据*/
var fireListDataDetail_rdsp = [];
var keyIssuesListData_rdsp = [];
var globalCardList = [];
var indexHiddenDangerStatus = 0; //0表示未处理1：表示已处理
var indexFlag = 0; //0表示列表，1表示首页或消息
var hiddenDangerListStatus = 0; //0 整改中 1核实中 2已完成
var equipIndex = -1; //设施监测列表，tab位置
var isChildPlatRole = false; //平台判断，是否在子平台
var searchFlag = 0; //1表示当前在搜索状态，
var searchEl = []; //搜索
var moreDectorStateIndex = 1; //设备物联【报警】列表bug1091
var isFromMessage = 0; //是否从message跳转出去
var pushMessageurl = "";
// var indexHistoryPoliceApply=0;//0全部  1未复位 2已复位  谁加的，什么意思？？？
var hasAnalogTypeArr = {
    "1": "压力",
    "2": "液位",
    "3": "设备电压",
    "4": "监测电压",
    "5": "温度",
    "6": "湿度",
    "7": "A相电压",
    "8": "B相电压",
    "9": "C相电压",
    "10": "A相电流",
    "11": "B相电流",
    "12": "C相电流",
    "13": "A相开关",
    "14": "B相开关",
    "15": "C相开关",
    "16": "开关",
    "17": "报警开关",
    "18": "常开开关",
    "19": "常关开关",
    "20": "剩余电流",
    "21": "氨气",
    "22": "硫化氢",
    "23": "甲烷",
    "24": "采样管压",
    "25": "进气湿度",
    "26": "进气温度",
    "30": "电气火灾A相电压",
    "31": "电气火灾B相电压",
    "32": "电气火灾C相电压",
    "33": "电气火灾A相电流",
    "34": "电气火灾B相电流",
    "35": "电气火灾C相电流",
    "36": "电气火灾A相温度",
    "37": "电气火灾B相温度",
    "38": "电气火灾C相温度",
    "39": "电气火灾剩余电流传感器",
    "40": "信号强度"
}

var nineCode = "";
var indoorId = '';
var indoorMapId = '';
var nineCodeName = "";
var bannerSwiper_lb = "";

/*--公共资源---------------------------------------------------------------------------------------*/
//登录之后获取公共资源 联网单位列表和区域下拉框数据
function getPublicReouse(searchOrgIds) {
    getUnitListAndSave(searchOrgIds);
    getCurrentAreaData();
    //获取分平台id
    getEveryPlatId();
    custom.getTestTask();
    native.getVersion();
    native.getjsVersion();
    native.checkVersion();
    native.checkH5Version();
}

function selectVenuesIdByAccount(cb) {
    Dao.selectVenuesIdByAccount_ajax({
        userName: userInfor.accountName,
        account: userInfor.accountName,
        deviceId: appKeyObj.deviceId
    }, function (data) {
        if (data) {
            nineCode = data.id;
            indoorId = data.indoorId;
            indoorMapId = data.indoorMapId;
            nineCodeName = data.name;
        }
        if (cb) {
            cb(data)
        }
    });
}

function getEveryPlatId(erro) {
    Dao.findOrgByOrgCode({
        userName: userInfor.accountName,
        deviceId: appKeyObj.deviceId,
        orgCode: platformCode || app.data.defaultPlatCode
    }, function (re) {
        if (re) {
            platformCodeId = re;
        }
    }, null, erro);
}

//获取当前没有处理的正在发生的警情
var currentPoliceList = [];

function getOtherPolice(orgId, callback) {
    common.loading(1)
    Dao.getFcfHistroyDataList({
        userName: userInfor.accountName,
        deviceId: appKeyObj.deviceId,
        orgIds: orgId,
        fireSystemId: '',
        categoryId: '',
        fireBuildingStructureId: '',
        fireTType: '',
        handlerStatus: '',
        startTime: "",
        endTime: "",
        dataType: 0,
        pageIndex: 0,
        pageSize: 100
    }, function (data, total) {
        common.loading(0)
        currentPoliceList = data ? data.listData : [];
        callback && callback()
    }, "", false);
}
//获取当前的手动报警
var currentManulAlarmList = [];

function getKeyAlarmList(orgId) {
    Dao.getKeyAlarmList({
        userName: userInfor.accountName,
        deviceId: appKeyObj.deviceId,
        organizationIds: orgId,
        queryType: 1,
        pageIndex: 0,
        pageSize: 100
    }, function (data, total) {
        currentManulAlarmList = data;
    }, "", false);
}

//获取建筑物列表
var saveBuildTreeData = [];
//保存联网单位列表数据
var currentUserUnitListData = [];
var searchUnitNameById = [];

function getUnitListAndSave(searchOrgIds) {
    Dao.moreUnitList({
        userName: userInfor.accountName,
        deviceId: appKeyObj.deviceId,
        orgIds: searchOrgIds || userInfor.organizationIds,
        areaId: 0,
        name: "",
        provinceId: 0,
        queryType: 0,
        pageIndex: 0,
        pageSize: 1000,
    }, function (data) {
        if (data && data.length > 0) {
            currentUserUnitListData = data;
            if (data.length == 1) {
                sessionStorage.setItem('unitListData', JSON.stringify(data))
            }
            jQuery.each(data, function (index, el) {
                searchUnitNameById[el.organizationId] = {
                    "organizationId": el.organizationId,
                    "shortName": el.shortName,
                    "longName": el.name,
                    "longitude": el.longitude,
                    "latitude": el.latitude,
                    "radius": 500,
                };
            });
        }
    }, false);
};

//保存区域下拉框数据
var currentPublicAreaData = [];

function getCurrentAreaData() {
    Dao.getAreaDataFormAjax({
        userName: userInfor.accountName,
        deviceId: appKeyObj.deviceId
    }, function (data) {
        if (data && data.length > 0) {
            currentPublicAreaData = data;
        }
    });
}

/*--方法---------------------------------------------------------------------------------------*/
//导航页面
function initPage(tabId) {
    jQuery(".index-tab").on('tab:show', onTabShow);
    if (tabId) {
        app.views.create('#' + tabId, {
            url: '/' + tabId + '/'
        });
    } else {
        showWitchMainPage(1);
    }
    //获取消息数据
    getUnReadMsgCount();
}

let clickTabFreshFalg = true

function onTabClick(tabId) {
    if (clickTabFreshFalg && tabId === app.data.currentActiveTab) {
        if (getClickEnabel(2000)) {
            //当前tab点击，刷新当前页
            if (tabId === 'home') {
                var router = $("#home :first-child").attr('data-page');
                if (router) {
                    if ('home' === router) {
                        app.view[1].router.currentPageEl.f7Component.refreshCards(1, function () {});
                        return;
                    }
                    var i;
                    var kanbanArray = ["/maintenceKanban/", "/soleKanban/", "/largeKanban/"];
                    for (i = app.view.length - 1; i >= 0; i--) {
                        var history = app.view[i].history[0];
                        if (history.indexOf("?loginId") > 1) {
                            history = history.substr(0, history.indexOf("?loginId"));
                        }
                        if (jQuery.inArray(history, kanbanArray) > -1) {
                            app.view[i].router.currentPageEl.f7Component.refreshCards(1, function () {});
                        }
                    }
                }
            } else if (tabId === 'monitor') {
                app.view.get("#monitor").router.currentPageEl.f7Component.refreshVedio(1, function () {});
            } else if (tabId === 'apply') {
                app.view.get("#apply").router.currentPageEl.f7Component.refreshCurrent(1, function () {});
            } else if (tabId === 'message') {
                app.view.get("#message").router.currentPageEl.f7Component.refreshMessage(1, function () {});
            } else if (tabId === 'mine') {
                app.view.get("#mine").router.currentPageEl.f7Component.refreshCurrent(1, function () {});
            }
        }
    }
    clickTabFreshFalg = true
}

/* function freshTab(tabId) {
    app.router.navigate('/' + tabId + '/', {
        ignoreCache: true,
        reloadCurrent: true,
    });
} */

function onTabShow(e) {
    clickTabFreshFalg = false
    var tabId = this.id;
    app.data.currentActiveTab = tabId;
    if (!app.views.get("#" + tabId)) {
        if (tabId == "home") {
            showWitchMainPage(1);
        } else {
            app.views.create('#' + tabId, {
                url: "/" + tabId + "/"
            });
        }
    }
    changeTabIcon(tabId);
    //如果有新的推送消息,刷新消息頁面
    if (IsNewMsg && (tabId == "message")) {
        native.receiveMessageTab();
    }
}


/*首页展示*/
// isNewPage 0:以前的看板 1:新的的看板
function showWitchMainPage(isNewPage, freshTab) {
    //根据角色进入不同的看板页
    for (let i = 0; i < userInfor.role.length; i++) {
        //九小用户
        if (jQuery.inArray(userInfor.role[i].id, nineUserId) > -1) {
            if (freshTab) {
                window.getCards_home(1, function () {});
            } else {
                app.views.create('#home', {
                    url: '/home/'
                });
            }
            break;
        }
        //单单位用户
        if (jQuery.inArray(userInfor.role[i].id, singleUserId) > -1) {
            if (isNewPage == 0) {
                /*  if (freshTab) { //已弃用
                     window.getCards_homeSingle(1, function () { });
                 } else {
                     app.views.create('#home', { url: '/homeSingle/' });
                 } */
            } else {
                if (freshTab) {
                    //window.getCards_soleKanban(1,function () {});
                } else {
                    app.views.create('#home', {
                        url: '/soleKanban/'
                    });
                }
            }
            break;
        }
        //多单位用户
        if (jQuery.inArray(userInfor.role[i].id, moreUserId) > -1) {
            if (isNewPage == 0) {
                /* if (freshTab) { //已弃用
                    window.getCards_homeMore(1, function () { });
                } else {
                    app.views.create('#home', { url: '/homeMore/' });
                } */
                if (userInfor.role[i].id == 141) {
                    app.methods.showToastCenter("超级管理员登录");
                }
            } else {
                if (freshTab) {
                    window.getCards_largeKanban(1, function () {});
                } else {
                    app.views.create('#home', {
                        url: '/largeKanban/'
                    });
                }
            }
            break;
        }
        //维保方
        if (jQuery.inArray(userInfor.role[i].id, maitenceUserId) > -1) {
            if (freshTab) {
                window.getCards_maintenceKanban(1, function () {});
            } else {
                app.views.create('#home', {
                    url: '/maintenceKanban/'
                });
            }
            break;
        }
    }
}

//切换图标
function changeTabIcon(tabId) {
    var tabIcons = $("#navPaegeCont .iconfont");
    for (var i = 0; i < tabIcons.length; i++) {
        if (tabIcons[i].className.indexOf(tabId) == -1) {
            tabIcons[i].className = tabIcons[i].className.replace("kuai", "xian");
        } else {
            tabIcons[i].className = tabIcons[i].className.replace("xian", "kuai");
        }
    }
}


/*--区域picker---------------------------------------------------------------------------------------*/
//获取区域数据
var saveAreaData = {};

function getAreaData(pickerID, showNameDom, callback) {
    saveAreaData = {};
    app.data.areaData = [];
    var provinceNameData = [];
    var cityNameData = [];
    var countyNameData = [];

    if (currentPublicAreaData.length > 0) {
        var data = currentPublicAreaData;
        if (data && data.length > 0) {
            for (var i = 0; i < data.length; i++) {
                var cProvinceName = data[i].name;
                saveAreaData[cProvinceName] = {
                    'id': data[i].id,
                    'nodes': {}
                };
                var cCityData = data[i].nodes;
                //省
                provinceNameData.push(cProvinceName);
                //市
                if (cCityData && cCityData.length > 0) {
                    var putCity = [];
                    for (var j = 0; j < cCityData.length; j++) {
                        var cCityName = cCityData[j].name;
                        saveAreaData[cProvinceName].nodes[cCityName] = cCityData[j].id;
                        var cCountyData = cCityData[j].area;
                        putCity.push(cCityName);
                        //县
                        if (cCountyData) {
                            cCountyData.unshift("-请选择-");
                            countyNameData[cCityName] = cCountyData;
                        }
                    }
                    putCity.unshift("-请选择-");
                    cityNameData[cProvinceName] = putCity;
                    cityNameData["-请选择-"] = ["-请选择-"];
                    if (countyNameData.length > 0) {
                        countyNameData["-请选择-"] = ["-请选择-"];
                    }
                }
            }
        }
        app.data.areaData.province = provinceNameData;
        app.data.areaData.province.unshift("全国");
        app.data.areaData.city = cityNameData;
        if (countyNameData.length > 0) {
            app.data.areaData.county = countyNameData;
        }
        initUnitCity(pickerID, showNameDom, countyNameData.length, callback);
    }
}

//初始化区域picker
var pickerCustomToolbar = null;

function initUnitCity(bindDom, showNameDom, status, callback) {
    var currentProvince = [];
    var currentCity = [];
    var currentCountry = [];
    var popupDom = "";
    var showDom = "";
    var firstP = "-请选择-";
    currentProvince = app.data.areaData.province;
    currentCity = app.data.areaData.city[firstP];
    if (status != 0) {
        currentCountry = app.data.areaData.county[firstP];
    }
    if (bindDom && showNameDom) {
        popupDom = bindDom;
        showDom = showNameDom;
    } else {
        popupDom = "changeUnitPopup";
        showDom = "positionArea";
    }
    if (pickerCustomToolbar) {
        pickerCustomToolbar.destroy();
    }
    var cols = [{
            textAlign: 'left',
            width: 160,
            values: currentProvince,
            onChange: function (picker, country) {
                if (picker.cols[1].replaceValues) {
                    if (country == "全国") {
                        country = "-请选择-";
                    }
                    picker.cols[1].replaceValues(app.data.areaData.city[country]);
                }
            }
        },
        {
            textAlign: 'center',
            width: 170,
            values: currentCity,
            onChange: function (picker, country) {
                if (picker.cols[2] && picker.cols[2].replaceValues) {
                    picker.cols[2].replaceValues(app.data.areaData.county[country]);
                }
            }
        }
    ];
    if (status != 0) {
        cols[2] = {
            textAlign: 'right',
            values: currentCountry,
            width: 160
        };
    }
    pickerCustomToolbar = app.picker.create({
        inputEl: '#' + popupDom,
        rotateEffect: true,
        renderToolbar: function () {
            return '<div class="toolbar">' +
                '<div class="toolbar-inner">' +
                '<div class="left">' +
                '<a href="#" class="link sheet-close popover-close toolbar-randomize-link">取消</a>' +
                '</div>' +
                '<div class="right">' +
                '<a href="#" class="link sheet-close popover-close quit-area">确定</a>' +
                '</div>' +
                '</div>' +
                '</div>';
        },
        cols: cols,
        on: {
            open: function (picker) {
                picker.$el.find('.quit-area').on('click', function (e) {
                    var index = picker.getValue().indexOf("-请选择-");
                    if (index == 1) { //选择省 全国
                        $("#" + showDom).html(picker.getValue()[0]);
                        if (picker.getValue()[0] != '全国') {
                            callback({
                                'areaId': 0,
                                'provinceId': saveAreaData[picker.getValue()[0]].id,
                                'name': ''
                            });
                        } else {
                            callback({
                                'areaId': 0,
                                'provinceId': 0,
                                'name': ''
                            });
                        }
                    } else {
                        $("#" + showDom).html(picker.getValue()[1]);
                        callback({
                            'areaId': saveAreaData[picker.getValue()[0]].nodes[picker.getValue()[1]],
                            'provinceId': 0,
                            'name': ''
                        });
                    }
                });
            },
        }
    });
}

var toptengetview = "";
//选择最近的报警设备
function ToptenviewFunc(callback, orgid) {
    common.loading(1);
    var url = staticPath + "pages/apply/dayCareApplyPage/Topten.html"
    app.request({
        url: url,
        dataType: 'text/html',
        success: function (data) {
            toptengetview = app.popup.create({
                content: data
            });
            // Open it
            toptengetview.open();
            //Close it
            jQuery("#unitPopupClose_topten").click(function (event) {
                toptengetview.close();
            });
            createToptenview(callback, orgid);
        }
    });
}

function createToptenview(callback, orgid) {
    Dao.getFcfHistroyDataList({
        userName: userInfor.accountName,
        deviceId: appKeyObj.deviceId,
        orgIds: orgid.toString(),
        fireSystemId: '',
        fireBuildingStructureId: '',
        fireTType: 10,
        pageIndex: 0,
        pageSize: 10,
    }, function (_data) {
        let data = _data ? _data.listData : []
        acommon.loading(0);
        if (data && data.length > 0) {
            data = data;
            if (data && data.length > 0) {
                for (var i = 0; i < data.length; i++) {
                    var statueimage = '';
                    statueimage = '<img src="' + staticPath + 'img/dectorState/alarm_bq.png" >&nbsp;&nbsp;';
                    $(".toptenlist ul").append(`
                        <li>
                          <a href="#" class="item-link item-content topviewlist" id="` + data[i].id + `_` + common.transNullundefined(data[i].fcFacilitiesName) + `">
                            <div class="item-media" style="padding-top:20px;">
                                <img src=" ` + staticPath + `img/UnitRealtimeState/unit_all.png" class="imgicon">
                            </div>
                            <div class="item-inner">
                              <div class="item-title-row">
                                <div class="item-title">` + statueimage + common.transNullundefined(data[i].fcFacilitiesName) + `</div>
                                <div class="item-after" style="width:50px;">

                                </div>
                              </div>
                              <div class="item-title-row">
                                <div class="item-title" style="font-size: 12px;" id="layerLocation_` + data[i].id + `">` + common.transNullundefined(data[i].fcfLocation) + `</div>
                                <div class="item-after" style="font-size: 12px;">` + common.transNullundefined(data[i].createTime) + `</div>
                              </div>
                            </div>
                          </a>
                        </li>
                    `);
                }
                $(".topviewlist").click(function (event) {
                    var fcfId = this.id.split("_")[0];
                    var fcfName = this.id.split("_")[1];
                    callback({
                        "fcfId": fcfId,
                        "fcfName": fcfName
                    });
                    app.popup.close();
                });
            }
        }
    }, function (e) {
        acommon.loading(0);
        app.methods.showToastBottom("获取警情记录列表失败");
    });
}



/*--建筑物选择---------------------------------------------------------------------------------------*/
//建筑物选择--公共页面
var currentBreadBuildId = 0;
var currentIndoorId = 0;
var breadBuildArr = [0];
var buildSelectChildData = [];
var buildSelectAllData = [];
var loadSelectBuildPopup = "";
var dataCallBack = null;

function loadSelectBuildFun(orgId, callback) {
    if (!getClickEnabel()) return
    var buildPage = "";
    currentBreadBuildId = 0;
    currentIndoorId = 0;
    breadBuildArr = [0];
    buildSelectChildData = [];
    buildSelectAllData = [];
    dataCallBack = callback;
    app.request({
        url: staticPath + "pages/common/selectBuildPage.html",
        dataType: 'text/html',
        success: function (data) {

            buildPage = data;
            loadSelectBuildPopup = app.popup.create({
                content: buildPage
            });
            // Open it
            loadSelectBuildPopup.open();

            //设置高度
            jQuery(".buildPopup-list").css({
                "height": (loadSelectBuildPopup.el.clientHeight - 75) + "px",
                "overflow": "auto"
            });

            //获取建筑物列表数据
            getMorePopupBuild(orgId);

            jQuery("#buildPopupClose").click(function (event) {
                loadSelectBuildPopup.close();
            });
            jQuery("#build_bread_quit").click(function (event) {
                var buildName = $("#build_bread_name_" + currentBreadBuildId).html();
                var isAddLayeredGraph = "";
                var layeredGraphUrl = "";
                if (currentBreadBuildId == 0) {
                    buildName = buildSelectAllData[0].text;
                    isAddLayeredGraph = "";
                } else {
                    isAddLayeredGraph = searchBuildNameById[currentBreadBuildId].isAddLayeredGraph;
                    layeredGraphUrl = searchBuildNameById[currentBreadBuildId].layeredGraphUrl;
                }
                callback({
                    "buildId": currentBreadBuildId,
                    "buildName": buildName,
                    "indoorId": currentIndoorId,
                    "isAddLayeredGraph": isAddLayeredGraph,
                    "layeredGraphUrl": layeredGraphUrl,
                });
                loadSelectBuildPopup.close();
            });
        }
    });
}

var searchBuildNameById = [];

function getMorePopupBuild(orgId, isNext) {
    var currentBdata = [];
    $(".buildPopup-list ul").empty();
    if (isNext) {
        if (orgId == 0) {
            currentBdata = buildSelectAllData;
        } else {
            currentBdata = buildSelectChildData[orgId];
        }
    } else {
        Dao.getBuildDataFormAjax({
            userName: userInfor.accountName,
            deviceId: appKeyObj.deviceId,
            organizationId: orgId * 1,
            buildId: 0,
        }, function (data) {
            currentBdata = data;
            buildSelectAllData = data;
            handleData(data);
        }, false);
    }
    if (currentBdata && currentBdata.length > 0) {
        for (var i = 0; i < currentBdata.length; i++) {
            searchBuildNameById[currentBdata[i].id] = {
                "buildId": currentBdata[i].id,
                "buildName": currentBdata[i].text,
                "isAddLayeredGraph": currentBdata[i].isAddLayeredGraph,
                "layeredGraphUrl": currentBdata[i].layeredGraphUrl,
            };
            $(".buildPopup-list ul").append(` 
				<li>
		         <a href="javascript:void(0)" class="item-link item-content" onclick="getNextBuild(` + currentBdata[i].id + `,` + currentBdata[i].indoorId + `);">
		           <div class="item-media" style="min-width: auto !important;" >
		           		<img src="` + staticPath + `img/mine/mine-3.png" style="width: 20px;" />
		           </div>
		           <div class="item-inner">
		             <div class="item-title" id="bulid_name_` + currentBdata[i].id + `">` + common.transNullundefined(currentBdata[i].text) + `</div>
		           </div>
		         </a>
		       </li>
			`);
        }
    } else {
        // var buildName = $("#bulid_name_" + orgId).html();
        var buildName = searchBuildNameById[orgId].buildName;
        if (orgId == 0) {
            buildName = "建筑物";
        }
        dataCallBack({
            "buildId": orgId,
            "buildName": buildName,
            "indoorId": currentIndoorId,
            "isAddLayeredGraph": searchBuildNameById[orgId].isAddLayeredGraph,
            "layeredGraphUrl": searchBuildNameById[orgId].layeredGraphUrl,
        });
        loadSelectBuildPopup.close();
    }
}

function handleData(data) {
    for (var i = 0; i < data.length; i++) {
        buildSelectChildData[data[i].id] = data[i].nodes;
        if (data[i].nodes) {
            handleData(data[i].nodes);
        }
    }
}

function getNextBuild(buildId, indoorId) {
    if (indoorId) {
        currentIndoorId = indoorId;
    }
    addNextBuildBread(buildId);
}

function addNextBuildBread(buildId) {
    if (buildId == 0) {
        currentBreadBuildId = 0;
        breadBuildArr = [0];
        $(".build_bread_new").remove();
    } else if (buildId != currentBreadBuildId) {
        currentBreadBuildId = buildId;
        //选择已经有的
        if (breadBuildArr.indexOf(buildId) > -1) {
            var delIndex = breadBuildArr.indexOf(buildId) + 1;
            for (var i = delIndex; i < breadBuildArr.length; i++) {
                $("#build_" + breadBuildArr[i]).remove();
                delete breadBuildArr[i];
            }
        } else {
            var name = $("#bulid_name_" + buildId).html();
            $(".buildPopup-bread-content").append(`
				<div class="buildPopup-bread link build_bread_new" id="build_` + buildId + `" onclick="addNextBuildBread(` + buildId + `)">
			    	<span id="build_bread_name_` + buildId + `">` + name + `</span>
			    	<i class="iconfont icon-jiantou" style="font-size: 13px;"></i>
			    </div>`);
            breadBuildArr.push(buildId);
        }
    }
    getMorePopupBuild(buildId, 1);
}


function getUnReadMsgCount() {
    Dao.getUnReadMsgCount({
        userName: userInfor.accountName,
        deviceId: appKeyObj.deviceId,
        orgIds: userInfor.organizationIds,
        orgCode: platformCode || app.data.defaultPlatCode,
        userOrgCode: userInfor.org.orgCode
    }, function (data) {
        if (data && data > 0) {
            $("#redpoint_tab_msg").show();
            $("#message_num").css('display', 'flex');
            // $("#unreadMessages").html(data<100?data+"条未读消息":'99+'+"条未读消息");
            // jQuery("#contactslist").css("margin-top","0px");
            // jQuery("#message_preloader").css("top","-38px");
        } else {
            // jQuery("#contactslist").css("margin-top","70px");
            // jQuery("#message_preloader").css("top", "30px");
            $("#redpoint_tab_msg").hide();
            $("#message_num").hide();
        }
    }, false);
}



/*巡检，隐患页面提示*/
function tipsDialog(text, btn1, btn2, btn1Back, icon, btn2Back) {
    var iconIn = "";
    if (!icon) {
        iconIn = staticPath + "img/hidden/hide-check.png";
    } else {
        iconIn = icon;
    }
    let html = `
        <div class="dialog-content">
            <i class="f7-icons dialog-close-rdsp">close</i>
            <div class="dialog-icon"><img src="` + iconIn + `" /></div>
            <div class="dialog-text-rdsp">` + text + `</div>
            <div class="btn_1">` + btn1 + `</div>
            <div class="btn_2">` + btn2 + `</div>
        </div>
    `;
    openLayer(html, (el) => {
        jQuery(".dialog-content .btn_1").off().click(function (event) {
            if (btn1Back) {
                btn1Back();
            }
        });
        jQuery(".dialog-content .btn_2").off().click(function (event) {
            if (btn2Back) {
                btn2Back();
            }
            layer.closeAll();
        });
        jQuery(".dialog-close-rdsp").off().click(function (event) {
            layer.closeAll();
        });
    }, "tips-dialog");
}

function voiceDialog(text, icon, callback) {
    let html = `
        <div class="dialog-content" style="margin-bottom: 0px">
            <i class="f7-icons dialog-close-rdsp">close</i>
            <div class="dialog-icon"><i class="mic-icon"></i></div>
            <div class="dialog-text-rdsp" style="color: #fff;margin-bottom:20px">` + text + `</div>
            <div class="dialog-text-rdsp" style="color: #fff;font-size: 10px;margin-bottom: 0px;margin-top: 0px;">语音识别能力由讯飞输入法提供</div>
        </div>
    `;
    openVoiceLayer(html, (el) => {
        jQuery(".dialog-close-rdsp").off().click(function (event) {
            if (callback) {
                callback();
            }
        });
        // jQuery(".layui-m-layershade").off().click(function(event) {
        //     if (callback){
        //         callback();
        //     }
        // });
    }, "tips-dialog");
}



/*一并处理警情--公共页面*/
function getNeedDealPolices(orgId, callback, isHome, value, eltype, dataType, dealPoliceId) {
    getOtherPolice(orgId, () => {
        var policeHtml = "";
        var showType = 0;
        var typeTotal = 0;
        var check_point_array = value;
        if (localStorage.getItem("rdsp_search_records")) {
            jQuery(".rdsp-dector-popup-top").show();
            dectorRecords = JSON.parse(localStorage.getItem("rdsp_search_records"));
        } else {
            jQuery(".rdsp-dector-popup-top").hide();
        }
        jQuery("#dector_police_list").empty();
        //列表
        if (currentPoliceList.length > 0) {
            for (var i = 0; i < currentPoliceList.length; i++) {
                //全部警情信息
                var data = currentPoliceList[i];
                var imageName = "";
                if (data.detailPic) {
                    imageName = JSON.parse(data.detailPic).detailIcon;
                }
                var suoshuHtml = "";
                var height = 100;
                if (userInfor.isMuilUnitUser == 1) {
                    suoshuHtml = `<div class="item-text item-title" >
                                    <span class="decter-mesage">所属单位：</span>
                                    <span class="decter-key-mesage" >` + common.transNullundefined(data.organizationName) + `</span>
                                </div>`;
                    height = 120;
                } else {
                    height = 100;
                }
                if (i == 0) {
                    policeHtml += `<li id="index-dealPolice` + data.id + `">
                        <label class="checkbox checkApply-checkbox checkApply-checkbox-` + data.id + `" data-fcFacilitiesId="` + data.fcFacilitiesId + `" data-createTime="` + data.createTime + `" data-id="` + data.id + `" style="position:absolute;top:36px;">
                            <input type="checkbox" id="mycheckbox` + data.id + `">
                            <i class="icon-checkbox"></i>
                        </label>
                        <div class="" style="padding-left:30px;padding-top:6px;">
                            <img src="` + imageName + `" class="myicon" width="80" style="position:absolute;width:70px;">
                            <div style="padding-left:78px;">
                            <div class="item-title-row">
                                <div class="item-title">
                                    <span >` + transFireIcon(data.fireTTypes) + `</span>
                                    <span class="decter-name">` + common.transNullundefinedToline(data.name) + `</span>
                                </div>
                            </div>
                            <div class="item-subtitle decter-mesage" style="margin-top: 8px;margin-bottom: 8px;">` + common.transNullundefined(data.fcFacilitiesAddress) + `</div>
                            ` + suoshuHtml + `
                                <div class="item-text">
                                    <span class="decter-mesage item-title">时间：</span>
                                    <span class="decter-key-mesage" style="font-size:12px;" >` + moment(data.createTime).format("YYYY-MM-DD HH:mm") + `</span>
                                </div>
                            </div>
                        </div>
                    </li>`;
                } else {
                    policeHtml += `<li style="height: ` + height + `px;border-top: solid 1px #E7E7E7;" id="index-dealPolice` + data.id + `">
                                    <label class="checkbox checkApply-checkbox checkApply-checkbox-` + data.id + `" data-fcFacilitiesId="` + data.fcFacilitiesId + `" data-createTime="` + data.createTime + `" data-id="` + data.id + `" style="position:absolute;top:36px;">
                                        <input type="checkbox" id="mycheckbox` + data.id + `">
                                        <i class="icon-checkbox"></i>
                                    </label>
                                        <div class="" style="padding-left:30px;padding-top:6px;">
                                            <img src="` + imageName + `" class="myicon" width="80" style="position:absolute;width:70px;">
                                            <div style="padding-left:78px;">
                                            <div class="item-title-row">
                                                <div class="item-title">
                                                    <span >` + transFireIcon(data.fireTTypes) + `</span>
                                                    <span class="decter-name">` + common.transNullundefinedToline(data.name) + `</span>
                                                </div>
                                                </div>
                                                <div class="item-subtitle decter-mesage" style="margin-top: 8px;margin-bottom: 8px;">` + common.transNullundefined(data.fcFacilitiesAddress) + `</div>
                                                ` + suoshuHtml + `
                                                    <div class="item-text">
                                                    <span class="decter-mesage item-title">时间：</span>
                                                    <span class="decter-key-mesage" style="font-size:12px;" >` + moment(data.createTime).format("YYYY-MM-DD HH:mm") + `</span>
                                                    </div>
                                                </div>
                                            </div>
                                </li>`;
                }

            }
        } else if (currentPoliceList.length == 0) {
            policeHtml = `<div class="no-data-img"><img src="` + listNoDataPic() + `"/></div>`;
        }
        let html = `
            <div class="rdsp-dector-popup">
                <div class="rdsp-org-popup-top" style="margin:-16px -10px 0 0;font-size: 17px;color: #b5b4b4;padding-bottom:10px;">
                    <div style="position: absolute;color: black;font-size: 16px;margin-left: -10px;" >一并处理其他警情</div>
                    <div style="text-align:right;" id="cancel_police_list" >X</div>
                </div>
                <div class="rdsp-dector-popup-bottom">
                    <div class="rdsp-dector-list rdsp-dector-list-height list" style="margin-top:10px;height: 360px;overflow-y: auto;margin:0 -26px 29px -26px">
                        <div class="sort_box" id="dector_police_list" style="width: 90%;margin:0 auto;padding-bottom: 50px;"><ul>` + policeHtml + `</ul></div>
                        <div id="letter"></div>
                    </div>
                </div>
                <div class="initials"><ul><li></li></ul></div>
        </div>
        <div id="enable-police-list" style="height: 36px;line-height: 36px;font-size: 15px;text-align: center;color: #fff;float: right;background-color: #378bf6; border-radius: 28px;width:68%;position: absolute;bottom: 13px;left:17%;z-index: 99;">确认</div>
        `;
        openLayer(html, (el) => {
            jQuery("#cancel_police_list").off().click((event) => {
                layer.closeAll();
            });
            //勾选
            jQuery(".checkApply-checkbox").off().click(function (event) {
                let id = jQuery(event.currentTarget).attr("data-id");
                let createTime = jQuery(event.currentTarget).attr("data-createTime");
                let fcFacilitiesId = jQuery(event.currentTarget).attr("data-fcFacilitiesId");
                var isHave = true; //判断是选中状态还是未选中状态
                var index = 0;
                for (var i = 0; i < check_point_array.length; i++) {
                    if (check_point_array[i].id == id) {
                        isHave = false;
                        index = i;
                    }
                }
                if (isHave) {
                    var obj = {};
                    obj.id = id;
                    obj.createTime = createTime;
                    obj.fcfId = fcFacilitiesId;
                    check_point_array.push(obj);
                } else {
                    check_point_array.splice(index, 1);
                }
            });
            jQuery("#enable-police-list").off().click((event) => {
                if (callback) {
                    callback({
                        "selectedIds": check_point_array
                    });
                }
                layer.closeAll();
            });
            //选中
            $(".each-dector-list").removeClass("active").css({
                "background-color": "",
                "color": "rgba(0,0,0,.87)"
            });
            if (value) {
                for (var i = 0; i < value.length; i++) {
                    $(".checkApply-checkbox-" + value[i].id).prop("checked", "checked");
                    $("#mycheckbox" + value[i].id).prop("checked", "checked");
                }
            }
            if (dealPoliceId) {
                $("#index-dealPolice" + dealPoliceId).hide();
            }
        });
    });

}
/*一并处理手动报警--公共页面*/
function getNeedManulAlart(orgId, callback, isHome, value, eltype, dataType) {
    //获取手动报警记录
    getKeyAlarmList(orgId);
    var policeHtml = "";
    var showType = 0;
    var typeTotal = 0;
    var check_point_array = value;
    if (localStorage.getItem("rdsp_search_records")) {
        jQuery(".rdsp-dector-popup-top").show();
        dectorRecords = JSON.parse(localStorage.getItem("rdsp_search_records"));
    } else {
        jQuery(".rdsp-dector-popup-top").hide();
    }
    jQuery("#dector_police_list").empty();
    //列表
    if (currentManulAlarmList.length > 0) {
        for (var i = 0; i < currentManulAlarmList.length; i++) {

            //全部警情信息
            var data = currentManulAlarmList[i];
            var imageName = "";
            if (data.icon && data.icon != "") {
                imageName = JSON.parse(data.icon).detailIcon;
            }
            var suoshuHtml = "";
            if (userInfor.isMuilUnitUser == 1) {
                suoshuHtml = `<div class="item-text item-title" >
                                <span class="decter-mesage">所属单位：</span>
                                <span class="decter-key-mesage" >` + common.transNullundefined(data.organizationName) + `</span>
                            </div>`;
            }
            if (data.handleList.length == 0) {
                policeHtml += `<li style="border-bottom:solid 1px #E7E7E7; display: flex; align-items: center;    padding: 10px 0;">
                    <label class="checkbox checkApply-checkbox checkApply-checkbox-` + data.id + `" data-createTime="` + data.createTime + `" data-fcFacilitiesId="` + data.fcFacilitiesId + `" data-id="` + data.id + `" >
                        <input type="checkbox" id="mycheckbox` + data.id + `">
                        <i class="icon-checkbox"></i>
                        </label>
                    <div class="right-block">                                      
                        <div style="padding-left:20px;">
                        <div class="item-title-row">
                            <div class="item-title" style=" white-space: normal;">
                                <span class="decter-name" style="word-break: break-all;font-size:14px">` + common.transNullundefinedToline(data.description) + `</span>
                            </div>
                        </div>
                        <div class="item-subtitle decter-mesage" style="margin-bottom: 5px;"></div>

                            <div class="item-text">
                                <span class="decter-mesage item-title">报警人：</span>
                                <span class="decter-key-mesage" style="font-size:12px;" >` + common.transNullundefined(data.createName) + `</span>
                                <span class="decter-key-mesage" style="font-size:12px;" >` + common.transNullundefined(data.phone) + `</span>
                            </div>
                        </div>
                    </div>
                </li>`;
            }
        }
    } else {
        policeHtml = "暂无其他警情";
    }
    let html = `
        <div class="rdsp-dector-popup">
            <div class="rdsp-org-popup-top">
                <div style="text-align:right;" id="cancel_police_list" >X</div>
            </div>
            <div class="rdsp-dector-popup-bottom">
                <div class="rdsp-dector-list rdsp-dector-list-height list" style="margin-top:10px;height: 300px;overflow-y: auto;">
                    <div class="sort_box" id="dector_police_list" ><ul>` + policeHtml + `</ul></div>
                    <div id="letter"></div>
                </div>
            </div>
            <div class="initials"><ul><li></li></ul></div>
    </div>
    <div id="enable-police-list" style="height: 36px;line-height: 36px;font-size: 15px;text-align: center;color: #fff;float: right;background-color: #378bf6; border-radius: 28px;width:67%;position: absolute;bottom: 13px;left: 52px;">确认</div>
    `;
    openLayer(html, (el) => {
        jQuery("#cancel_police_list").off().click((event) => {
            layer.closeAll();
        });
        //勾选
        jQuery(".checkApply-checkbox").off().click(function (event) {
            let id = jQuery(event.currentTarget).attr("data-id");
            let createTime = jQuery(event.currentTarget).attr("data-createTime");
            let fcFacilitiesId = jQuery(event.currentTarget).attr("data-fcFacilitiesId");
            var isHave = true; //判断是选中状态还是未选中状态
            var index = 0;
            for (var i = 0; i < check_point_array.length; i++) {
                if (check_point_array[i].id == id) {
                    isHave = false;
                    index = i;
                }
            }
            if (isHave) {
                var obj = {};
                obj.id = id;
                obj.createTime = createTime;
                obj.fcfId = fcFacilitiesId;
                check_point_array.push(obj);
            } else {
                check_point_array.splice(index, 1);
            }
        });
        jQuery("#enable-police-list").off().click((event) => {
            if (callback) {
                callback({
                    "selectedIds": check_point_array
                });
            }
            layer.closeAll();
        });
        //选中
        $(".each-dector-list").removeClass("active").css({
            "background-color": "",
            "color": "rgba(0,0,0,.87)"
        });
        if (value) {
            for (var i = 0; i < value.length; i++) {
                $(".checkApply-checkbox-" + value[i].id).prop("checked", "checked");
                $("#mycheckbox" + value[i].id).prop("checked", "checked");
            }
        }
    });
}


/*筛选日期*/
//type 0:年 1:年月 2：月日
function selectDate_Fn(type, callback, value) {
    if (!getClickEnabel()) return
    var timeArray = common.getTimeArray(type);
    var html = "";
    var listHtml = "";
    if (timeArray.length > 0) {
        for (var i = 0; i < timeArray.length; i++) {
            var text = timeArray[i].name;
            if (type == 0) {
                text = timeArray[i].name;
            } else if (type == 1) {
                text = timeArray[i].name;
            } else if (type == 2) {
                text = text.split("年")[1];
            }
            listHtml += `<div class="rdsp-option-list rdsp-option-list-border" index-id=` + i + ` id="lastOptionId_` + timeArray[i].id + `" data-id="` + timeArray[i].id + `" data-text = "` + timeArray[i].name + `">` + common.transNullundefined(text) + `</div>`;
        }
        listHtml += `<div class="rdsp-option-list-bottomline">我是有底线的</div>`;

        html = `<div class="rdsp-selectOption">` + listHtml + `</div>`;
        openLayer(html, (el) => {
            jQuery(".rdsp-option-list").off().click(function (event) {
                let index = jQuery(event.currentTarget).attr("index-id");
                let id = jQuery(event.currentTarget).attr("data-id");
                let name = jQuery(event.currentTarget).attr("data-text");
                if (callback) {
                    var startTime = "";
                    var endTime = "";
                    if (type == 0) {
                        startTime = name.replace("年", "");
                        endTime = "";
                    } else if (type == 1) {
                        startTime = name.replace("年", "-").replace("月", "-") + "01 " + "00:00:00";
                        var totalDay = mGetDate(name.split("年")[0], name.split("年")[1].split("月")[0]);
                        endTime = name.replace("年", "-").replace("月", "-") + totalDay + " 23:59:59";
                    } else if (type == 2) {
                        startTime = name.replace("年", "-").replace("月", "-").replace("日", " ") + "00:00:00";
                        endTime = name.replace("年", "-").replace("月", "-").replace("日", " ") + "23:59:59";
                    }
                    callback({
                        "id": id,
                        "startTime": startTime,
                        "endTime": endTime,
                        "index": index
                    });
                    layer.closeAll();
                }
            });
            //选中
            $(".rdsp-option-list").removeClass("active");
            if (value !== "") {
                $(".rdsp-selectOption").scrollTop(parseInt(40 * value));
                $(".rdsp-option-list").eq(value).addClass('active');
            }
        });
    }
}

/*获取月份天数*/
function mGetDate(year, month) {
    var d = new Date(year, month, 0);
    return d.getDate();
}



// /*语音输入动画*/
// function voiceInputAnimation(callback){
//     var html = `<i class="mic-icon"></i><p>请开始说话</p>`;
//     openVoiceLayer(html,(el)=>{
//         jQuery(".layui-m-layermain").off().click(function(event) {
//             if(callback){
//                 callback();
//                 layer.closeAll();
//             }
//         });
//     });
// }

/*搜索*/
function searchPouper_fn(callback, el) {
    searchFlag = 1;
    searchEl = el;
    el.parents(".navbar-inner").append(`<div class="nav-search-input-container">
        <div class="nav-search-input-back">
            <span class="iconfont icon-zuo"></span>
        </div>
        <input type="text" id="search-page-input" placeholder="请输入关键字">
        <div class="search-btn">搜索</div>
    </div>`);
    el.parents(".navbar-inner").children().hide();
    el.parents(".navbar-inner").find(".nav-search-input-container").show();
    jQuery("#search-page-input").focus();
    //取消
    jQuery(".nav-search-input-back").off().click(function (event) {
        searchFlag = 0;
        searchEl = [];
        if (callback) {
            callback("");
        }
        el.parents(".navbar-inner").children().show();
        el.parents(".navbar-inner").find(".nav-search-input-container").remove();
    });
    //enter
    jQuery("#search-page-input").keypress(function (e) {
        let name = jQuery("#search-page-input").val();
        if (e.which == 13) {
            if (callback) {
                callback(name);
            }
        };
    });
    jQuery(".search-btn").click(function () {
        let name = jQuery("#search-page-input").val();
        if (callback) {
            callback(name);
        }
    });
}

/*时间插件*/
function chooseDate(el, callback, dateType) {
    jQuery.date(el, {
        type: dateType ? dateType : "YYYY-MM-DD",
        beginYear: "2010",
        endYear: "2088",
        location: "before",
    });
    jQuery(el).click(function () {
        jQuery(".date-shade-content").show();
    });
    jQuery("#d-confirm").click(function () {
        jQuery(".date-shade-content").hide();
        var date = jQuery(el).attr("date-value");
        var dateStr = date + " 00:00:00";
        var dateEnd = date + " 23:59:59";
        callback({
            startTime: dateStr,
            endTime: dateEnd
        });
    });
    jQuery("#d-cancel").click(function () {
        jQuery(el).removeAttr("date-value");
        jQuery(".date-shade-content").hide();
    });
}


/*--点击间隔--------------------------------------------------------------------------------------------*/

//点击间隔
var _clickEnable;
var dfcpClickEnable = true;
// 获取点击事件许可
var getClickEnabel = function (delayTime) {
    if (dfcpClickEnable) {
        setClickDisabled(delayTime);
        return true;
    }
    return false;
}
// 设置不可用
var setClickDisabled = function (delayTime) {
    dfcpClickEnable = false;
    if (_clickEnable != null) {
        clearTimeout(_clickEnable);
    }
    _clickEnable = null;
    _clickEnable = setTimeout(setClickEnable, delayTime ? delayTime : 500);
}
// 设置可用
var setClickEnable = function () {
    dfcpClickEnable = true;
}


/*--弹窗--------------------------------------------------------------------------------------------*/

function openLayer(html, successBack, className, value) {
    layer.closeAll();
    let layerIndex = layer.open({
        content: html,
        className: className ? className : 'rdsp-popuo-html',
        style: 'background-color:#fff;border:none;max-width: 300px;max-height: 80vh;overflow: hidden;overflow-y: auto;',
        anim: 'up',
        success: function (elem) {
            if (successBack) {
                successBack(elem, value);
            }
        }
    });
}


function openVoiceLayer(html, successBack, className, value) {
    layer.closeAll();
    let layerIndex = layer.open({
        content: html,
        type: 1,
        shadeClose: false,
        className: className ? className : 'rdsp-popuo-html',
        style: 'background-color:rgba(0,0,0,0.8);border:none;max-width: 640px;',
        anim: 'up',
        success: function (elem) {
            if (successBack) {
                successBack(elem, value);
            }
        }
    });
}



/*--空状态--------------------------------------------------------------------------------------------*/

//默认logo
function transLogo(url) {
    if (url) {
        return url;
    } else {
        return staticPath + 'img/default/emptyUnit.png';
    }
}

/*无数据图片*/
function listNoDataPic(url) {
    if (url) {
        return url;
    } else {
        return staticPath + 'img/emptyImg/defaultnone.png';
    }
}
/*多单位报表——无高危单位*/
function listNoDangeroust(url) {
    if (url) {
        return url;
    } else {
        return staticPath + 'img/emptyImg/noDangeroust.png';
    }
}
/*无图片*/
function picNo(url) {
    if (url) {
        return url;
    } else {
        return staticPath + 'img/emptyImg/bynone.png';
    }
}
/*无头像图片*/
function picPeopleNo(url) {
    if (url) {
        return url;
    } else {
        return staticPath + 'img/mine/defaulticon.png';
    }
}
/*无探测器*/
function picDecterNo(url) {
    if (url) {
        return url;
    } else {
        return staticPath + "img/mine/defEqIcon.png";
    }
}
/*无视频*/
function picVedioNo(url) {
    if (url) {
        return url + '?imageView2/2/w/432/h/288/q/75';
    } else {
        return REMOTESTATICPATH + "/" + platformCode + "/h5/pic/bg-video.png";
        // if (platformCode == "zhuhai" || platformCode == "chshzhxf") {
        //     return staticPath + "img/vedio/zhuhaidefaultVideo.png";
        // } else {
        //     return staticPath + "img/vedio/defaultVideo.png";
        // }
    }
}

/* 点位默认图片 */
function picCheckPoint(url) {
    if (url) {
        return url;
    } else {
        return staticPath + "img/emptyImg/default_check.png";
    }
}


/*--报警状态图标--------------------------------------------------------------------------------------------*/
function transFireIcon(fire) {
    let text = "";
    let type = "";
    if (fire) {
        type = fire.toString();
        if (type.indexOf("10") > -1) {
            text = "<span class='rdsp-icon fire-icon'>报警</span>";
        } else if (type.indexOf("20") > -1) {
            text = "<span class='rdsp-icon fault-icon'>故障</span>";
        } else if (type.indexOf("30") > -1) {
            text = "<span class='rdsp-icon shielding-icon'>屏蔽</span>";
        } else if (type.indexOf("40") > -1) {
            text = "<span class='rdsp-icon linkage-icon'>联动</span>";
        } else {
            text = "<span class='rdsp-icon normal-icon'>正常</span>";
        }
        return text;
    } else {
        return "<span class='rdsp-icon normal-icon'>正常</span>";
    }
}

function transNewFireIcon(fire) {
    let text = "";
    let type = "";
    if (fire) {
        type = fire.toString();
        if (type.indexOf("10") > -1) {
            text = "icon-APPicon_baojing";
        } else if (type.indexOf("20") > -1) {
            text = "icon-APPicon_guzhang1";
        } else if (type.indexOf("30") > -1) {
            text = "icon-APPicon_pingbi";
        } else if (type.indexOf("40") > -1) {
            text = "icon-APPicon_liandong";
        } else {
            text = "icon-APPicon_zhengchang";
        }
        return text;
    } else {
        return "icon-APPicon_zhengchang";
    }
}

function transFireColorText(fire) {
    let text = "";
    let type = "";
    if (fire) {
        type = fire.toString();
        if (type.indexOf("10") > -1) {
            text = "<span class='fire-icon-color'>报警</span>";
        } else if (type.indexOf("20") > -1) {
            text = "<span class='fault-icon-color'>故障</span>";
        } else if (type.indexOf("30") > -1) {
            text = "<span class='shielding-icon-color'>屏蔽</span>";
        } else if (type.indexOf("40") > -1) {
            text = "<span class='linkage-icon-color'>联动</span>";
        } else {
            text = "<span class='normal-icon-color'>正常</span>";
        }
        return text;
    } else {
        return "<span class='normal-icon-color'>正常</span>";
    }
}

function transFireToText(fire) {
    let text = "";
    let type = "";
    if (fire) {
        type = fire.toString();
        if (type.indexOf("10") > -1) {
            text = "报警";
        } else if (type.indexOf("20") > -1) {
            text = "故障";
        } else if (type.indexOf("30") > -1) {
            text = "屏蔽";
        } else if (type.indexOf("40") > -1) {
            text = "联动";
        } else {
            text = "正常";
        }
        return text;
    } else {
        return "正常";
    }
}

function transFireColor(fire) {
    let text = "";
    let type = "";
    if (fire) {
        type = fire.toString();
        if (type.indexOf("10") > -1) {
            text = "#fe5259";
        } else if (type.indexOf("20") > -1) {
            text = "#f8b728";
        } else if (type.indexOf("30") > -1) {
            text = "#999";
        } else if (type.indexOf("40") > -1) {
            text = "#378bf6";
        } else {
            text = "#77be07";
        }
        return text;
    } else {
        return "#77be07";
    }
}
//showArr权限角色id  componentID要显示的组件id
function judgeAuthority(showArr, componentID) {
    var showFlag = false;
    jQuery.each(userInfor.role, function (index, obj) {
        if (showArr.indexOf(obj.id) > -1) {
            showFlag = true;
            return false;
        }
    });
    if (showFlag) {
        jQuery(componentID).show();
    } else {
        jQuery(componentID).hide();
    }
}
/*责任人选择增加字母搜索--公共页面*/
function selectOptionFnMoreBak(orgId, list, callback, value, type) {
    var listHtml = "";
    jQuery("#person_sort_list").empty();
    //列表
    if (list.length > 0) {
        for (var i = 0; i < list.length; i++) {
            listHtml += `<div class="sort_list each-org-list rdsp-sort-list-` + list[i].id + `" id="lastOptionId_` + i + `" index-id=` + i + ` data-type="1" data-id="` + list[i].id + `" data-text = "` + list[i].name + `">
                    <div class="num_name">` + common.transNullundefined(list[i].name) + `</div>
                </div>`;
        }
    }
    let html = `
        <div class="rdsp-org-popup" style="height:400px;">
            <div class="rdsp-org-popup-bottom">
                <div class="rdsp-org-list rdsp-org-list-height list" style="height: 378px;">
                    <div class="sort_box" id="person_sort_list" >` + listHtml + `</div>
                    <div id="letter"></div>
                </div>
            </div>
            <div class="initials" ><ul><li></li></ul></div>
    </div>`;

    openLayer(html, (el) => {
        stratSort();
        jQuery(".each-org-list").off().click((event) => {
            let index = jQuery(event.currentTarget).attr("index-id");
            let id = jQuery(event.currentTarget).attr("data-id");
            let name = jQuery(event.currentTarget).attr("data-text");
            if (callback) {
                callback({
                    "id": id,
                    "name": name,
                    "index": index
                });
            }
            layer.closeAll();
        });
        //选中
        $(".each-org-list").removeClass("active").css({
            "background-color": "",
            "color": "rgba(0,0,0,.87)"
        });
        if (value) {
            $("#lastOptionId_" + value).css({
                "background-color": "#4e9bff",
                "color": "#fff"
            });
        }

    });
}
//弹出框加载会更多
function selectOptionFnMore(orgId, list, callback, value, type) {
    var type = false;
    var html = "";
    var listHtml = "";

    if (list.length > 0) {
        for (var i = 0; i < list.length; i++) {
            if (i == list.length - 1) {
                listHtml += `<div class="sort_list rdsp-option-list" index-id=` + i + ` id="lastOptionId_` + i + `" data-id="` + list[i].id + `" data-text = "` + list[i].name + `">` + common.transNullundefined(list[i].name) + `</div>`;
            } else {
                listHtml += `<div class="sort_list rdsp-option-list rdsp-option-list-border" index-id=` + i + ` id="lastOptionId_` + list[i].id + `" data-id="` + list[i].id + `" data-text = "` + list[i].name + `">` + common.transNullundefined(list[i].name) + `</div>`;
            }
        }

        html = `<div class="rdsp-selectOption">
                    ` + listHtml + `
                    <div class="morePeople" onClick="getHaveOrgUserList(` + orgId + `)">加载更多</div>
                    <div class="initials" ><ul><li></li></ul></div>
                </div>
                `;
        openLayer(html, (el) => {
            jQuery(".rdsp-option-list").off().click(function (event) {
                let index = jQuery(event.currentTarget).attr("index-id");
                let id = jQuery(event.currentTarget).attr("data-id");
                let name = jQuery(event.currentTarget).attr("data-text");
                if (callback) {
                    callback({
                        "id": id,
                        "name": name,
                        "index": index
                    });
                    layer.closeAll();
                }
            });
            //选中
            $(".rdsp-option-list").removeClass("active");
            if (value) {
                $(".rdsp-selectOption").scrollTop(parseInt(40 * value));
                $(".rdsp-option-list").eq(value).addClass('active');
            }
        });
    }

}

function getHaveOrgUserList(orgId, e) {
    var self = this;
    var UserListHtml = "";
    $(".morePeople").html("其他拥有该单位权限的用户");
    if (e && e.stopPropagation) {
        //因此它支持W3C的stopPropagation()方法
        e.stopPropagation();
    } else {
        //否则，我们需要使用IE的方式来取消事件冒泡
        window.event.cancelBubble = true;
    };
    Dao.getHaveOrgUserList({
        userName: userInfor.accountName,
        deviceId: appKeyObj.deviceId,
        account: userInfor.accountName,
        pageSize: 25,
        queryType: 1,
        pageIndex: 0,
        orgId: orgId,
    }, function (data) {
        if (data != null && data.length != 0) {
            for (var i = 0; i < data.length > 0; i++) {
                UserListHtml += `<div class="rdsp-option-list rdsp-option-list-border" index-id=` + i + ` id="lastOptionId_` + data[i].orgId + `" data-id="` + data[i].orgId + `" data-text = "` + data[i].name + `">` + common.transNullundefined(data[i].name) + `</div>`;
            }
            $(".rdsp-selectOption").append(UserListHtml);
        }
    });
}

//责任人弹窗添加九小场所
function selectDutyAndNine(unitPeople, callback, index, type) {
    let html = `
        <div class="toolbar tabbar nine-duty-people" style="height:30px;background: transparent;">
            <div class="toolbar-inner" style="background-color: #FFF;">
                <a href="#tab-1" class="tab-link tab-link-active">单位用户</a>
                <a href="#tab-2" class="tab-link" id="selectDutyAndNine-tab-1">九小用户</a>
                <a href="#tab-3" class="tab-link" id="selectDutyAndNine-tab-2">其他用户</a>
                <a href="#tab-4" class="tab-link" id="selectDutyAndNine-tab-3">维保公司</a>
            </div>
        </div>
        <div class = "tabs" style="height:220px;" >
            <div class="tab tab-active" id="tab-1"></div>
            <div class="tab" id="tab-2"></div>
            <div class="tab" id="tab-3"></div>
            <div class="tab" id="tab-4"></div>
        </div>
    `;
    openLayer(html, (el) => {
        //单位用户
        var html1 = "";
        var html2 = "";
        var html3 = "";
        var html4 = "";

        //没有维保公司
        if (JSON.stringify(unitPeople).indexOf("weibaogongsi") < 0) {
            jQuery("#tab-4,#selectDutyAndNine-tab-3").hide();
        }

        for (var i = 0; i < unitPeople.length; i++) {
            if (unitPeople[i].type == 'danweiyonghu') {
                html1 += `<div class="rdsp-option-list rdsp-option-list-border" id="` + unitPeople[i].id + `" style="margin-left:10px;"
                data-text = "` + common.transNullundefined(unitPeople[i].name) + `" data-type="1">
                ` + (common.transNullundefined(unitPeople[i].name) + (unitPeople[i].postName ? (' - ' + unitPeople[i].postName) : '')) + `
                </div>`;
            }
            if (unitPeople[i].type == 'jiuxiaochangsuoyonghu') {
                showFlag2 = true;
                html2 += `<div class="rdsp-option-list rdsp-option-list-border" id="` + unitPeople[i].id + `" style="margin-left:10px;"
                data-text = "` + common.transNullundefined(unitPeople[i].name) + `" data-type="2">
                ` + (common.transNullundefined(unitPeople[i].name) + (unitPeople[i].postName ? (' - ' + unitPeople[i].postName) : '')) + `
                </div>`;
            }
            if (unitPeople[i].type == 'qitayonghu') {
                showFlag3 = true;
                html3 += `<div class="rdsp-option-list rdsp-option-list-border" id="` + unitPeople[i].id + `" style="margin-left:10px;"
                data-text = "` + common.transNullundefined(unitPeople[i].name) + `" data-type="3">
                ` + (common.transNullundefined(unitPeople[i].name) + (unitPeople[i].postName ? (' - ' + unitPeople[i].postName) : '')) + `
                </div>`;
            }
            if (unitPeople[i].type == 'weibaogongsi') {
                showFlag4 = true;
                html4 += `<div class="rdsp-option-list rdsp-option-list-border" id="` + unitPeople[i].id + `" style="margin-left:10px;"
                data-text = "` + common.transNullundefined(unitPeople[i].name) + `" data-type="4">
                ` + (common.transNullundefined(unitPeople[i].name) + (unitPeople[i].postName ? (' - ' + unitPeople[i].postName) : '')) + `
                </div>`;
            }
        }
        $("#tab-1").html(`<div class="rdsp-selectOption" style="height: 200px;overflow: auto;" >` + html1 + `</div>`);
        //九小场所用户
        $("#tab-2").html(`<div class="rdsp-selectOption" style="height: 200px;overflow: auto;">` + html2 + `</div>`);
        //其他用户
        $("#tab-3").html(`<div class="rdsp-selectOption" style="height: 200px;overflow: auto;">` + html3 + `</div>`);
        $("#tab-4").html(`<div class="rdsp-selectOption" style="height: 200px;overflow: auto;">` + html4 + `</div>`);
        jQuery(".rdsp-option-list").off().click(function (event) {
            let id = jQuery(event.currentTarget).attr("id");
            let name = jQuery(event.currentTarget).attr("data-text");
            let type = jQuery(event.currentTarget).attr("data-type");
            if (callback) {
                callback({
                    "id": id,
                    "name": name,
                    "type": type * 1,
                    "index": id
                });
                layer.closeAll();
            }
        });
        //选中
        if (type) {
            app.tab.show("#tab-" + type);
        } else {
            app.tab.show("#tab-1");
        }
        $(".rdsp-option-list").removeClass("active");
        if (index) {
            $("#tab-" + type + " #" + index).addClass('active');
        }
    });
}

//播放视频
function playCurrentVedio(bean, focus) {
    var videoBean = {};
    videoBean.id = bean.id;
    videoBean.deviceId = bean.deviceId;
    videoBean.type = bean.type;
    videoBean.name = bean.name;
    if (focus) {
        videoBean.id = bean.concemId;
        videoBean.type = bean.videoType;
        videoBean.name = bean.videoName;
    }
    videoBean.channel = bean.channel;
    videoBean.status = bean.status;
    videoBean.picUrl = bean.picUrl;
    videoBean.isOnline = bean.isOnline;
    videoBean.isConcem = bean.isConcem == null ? 0 : bean.isConcem;
    if (bean.type == 12) {
        app.router.navigate(`/videoPlayer/${bean.id}/${bean.deviceId}/${bean.name}/${videoBean.isConcem}/`);
        return
    }
    Dao.getAuthList({
        organizationId: bean.organizationId,
        equiptType: videoBean.type,
        orgCode: userInfor.org.orgCode,
        authId: bean.authId
    }, function (data) {
        var videoKeyBean = data[0];
        // 南京临时解决方案
        if (platformCode == "njsub") {
            videoKeyBean.type = videoKeyBean.type == 6 ? 5 : videoKeyBean.type;
            videoBean.type = videoBean.type == 6 ? 5 : videoBean.type;
        }
        native.openVideo(JSON.stringify(videoKeyBean), JSON.stringify(videoBean));
    });
}

/**
 * @Author: Chili
 * @Description: 上传图片组件
 * @Date: 2019-07-19 16:16:23
 */
let multNumber = 0;
let isOver = false;
let videoPopup = ''

function previewVideo() {
    jQuery(".video-icon").off().click(function (e) {
        let src = jQuery(e.currentTarget).attr("data-src");
        if (!videoPopup) {
            videoPopup = app.popup.create({
                content: `<div class="popup" style="background:#000;">
                    <video id="popupVideo" src="${src}" controls style="position: absolute;top:60px;left:0;width: 100%;height: calc(100% - 60px );background: #000;"></video>
                    <a class="link popup-close" href="#" style="position: absolute;top: 10px;right: 5px;z-index: 9;">
                        <i style="padding:5px 10px;color: #fff;font-size: 20px;" class="iconfont icon-guanbi"></i>
                    </a>
                </div>`,
                on: {
                    close: function () {
                        videoPopup.$el.find('#popupVideo').attr('src', '')
                    }
                }
            });
            videoPopup.open()
        } else {
            videoPopup.$el.find('#popupVideo').attr('src', src)
            videoPopup.open()
        }
    })
}

function upLoadImagesCompt($el, callback, multiple, number, container, picks, descript, allowVideo = false) {
    let curPage = app.view.current.el.f7View.router.currentPageEl.f7Component.pageName
    let con = 'upLoadImagesContainer';
    let pick = 'upLoadPickfiles';
    let des = `添加现场图片${allowVideo?'或视频':''}（必须）`;
    let index = 0;
    let isMultiple = multiple;
    multNumber = number ? number : 9;
    if (container) {
        con = container;
    }
    if (picks) {
        pick = picks;
    }
    if (descript) {
        des = descript;
    }
    $el.html(`
    <div class="upload-container-link" >
        <div class="up-content" id="` + con + `">
            <a class="" id="` + (pick) + `" href="#" >
                <i class="iconfont icon-weibiaoti-_tianjia"></i>
                <p>` + des + `</p>  
            </a>
        </div>
        <div id="upContain_` + pick + `"></div>
    </div>`);
    common.uploadImage(function (picUrl, pic) {
        var u = navigator.userAgent;
        var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
        var isIOS = u.indexOf('iPhone') > -1 || u.indexOf('iPad') > -1; //IOS
        let dotIndex = picUrl.lastIndexOf(".");
        let tv = picUrl.substring(dotIndex)
        if (isIOS || isAndroid) {
            if (!allowVideo) {
                if (tv == ".mp4" || tv == ".3gp" || tv == ".mpeg" || tv == ".mavip4" || tv == ".flv" || tv == ".mov") {
                    app.methods.showToastCenter("不允许上传视频，请重新选择");
                    return;
                }
            }
        }
        let upPicNumber = jQuery("#upContain_" + pick).children().length;
        if (upPicNumber < multNumber) {
            isOver = false;
            index++;
            callback(picUrl, "add");
            let newPic = '';
            if (tv == ".mp4" || tv == ".3gp" || tv == ".mpeg" || tv == ".mavip4" || tv == ".flv" || tv == ".mov") {
                newPic += `
                <div class='new-pic-item' id="` + container + `_` + picks + `_` + index + `" >
                    <div class="pic-item lazy lazy-fade-in"
                        style="background: url(img/common/video-detail.png);
                        background-position: center;
                        background-size: cover;
                        background-repeat: no-repeat;"
                        data-pic="` + (pic.imgsrc || picUrl) + `"
                        name= "` + (picUrl + `_` + new Date().getTime()) + `">
                    </div>
                    <div class="createTrouble_del createTrouble_del_` + index + `" data-index="` + index + `"></div>
                </div>`;
            } else {
                newPic += `
                <div class='new-pic-item' id="` + container + `_` + picks + `_` + index + `" >
                    <div class="pic-item lazy lazy-fade-in"
                        style="background: url(` + (pic.imgsrc || picUrl) + `);
                        background-position: center;
                        background-size: cover;
                        background-repeat: no-repeat;"
                        data-pic="` + (pic.imgsrc || picUrl) + `"
                        name= "` + (picUrl + `_` + new Date().getTime()) + `">
                    </div>
                    <div class="createTrouble_del createTrouble_del_` + index + `" data-index="` + index + `"></div>
                </div>`;
            }
            jQuery("#upContain_" + pick).append(newPic);
            app.lazy.create(".pic-item");
            //删除
            jQuery(".createTrouble_del_" + index).click(function (e) {
                index--;
                // let cindex = jQuery(e.currentTarget).attr("data-index");
                let cPic = jQuery(e.currentTarget).offsetParent().find(".pic-item").attr("data-pic");
                jQuery(e.currentTarget).parent().remove();
                callback(cPic, "delete");
                e.stopPropagation();
            });
            //点击查看大图
            jQuery(".new-pic-item").off().click(function (e) {
                let picArr = [];
                let cPic = jQuery(e.currentTarget).children().attr("data-pic");
                let arr = jQuery(e.currentTarget).parent().find(".pic-item");
                jQuery.each(arr, function (index, value) {
                    let img = jQuery(value).attr("data-pic");
                    picArr.push(img);
                });
                let picIndex = picArr.indexOf(cPic);
                openAndShowBigImage(picArr, picIndex);
                e.stopPropagation();
            })
            // 预览视频
            // previewVideo()
        } else {
            isOver = true;
            // if(isOver){
            //     isOver = false;
            // } else{
            //     isOver = true;
            // }
        }
        if (isOver) {
            app.methods.showToastCenter("请上传小于" + (multNumber + 1) + "张图片");
        }
    }, isMultiple, multNumber, container, picks, null, null, null, index);
}

/* 任务提示信息 */
//是否保存
function isSaveData(btnBack1, btnBack2) {
    let html = `
		  <div class="my-hint-main">
		    <div class="my-hint-top"><span>确认保存</span></div>
		    <div class="my-hint-body">
		      <div class="my-hint-text">
		        <span>您有输入内容，确认不保存么？</span>
		      </div>
		    </div>
		    <div class="my-hint-bottom">
		       <div class="block">
	  	         <p class="row">
	  	           <button class="col button button-big" id="noSave">不保存</button>
	  	           <button class="col button button-big button-fill" id="continue">返回继续</button>
	  	         </p>
	  		   </div>
		    </div>
		  </div>
		  `;
    openLayer(html, (el) => {
        jQuery("#noSave").off().click(function () {
            if (btnBack1) {
                layer.closeAll();
                btnBack1();
            }
        });

        jQuery("#continue").off().click(function () {
            if (btnBack2) {
                layer.closeAll();
                btnBack2();
            }
        });
    });
}

//撤销
function cancelTask(btnBack2) {
    let html = `
	  <div class="my-hint-main">
	    <div class="my-hint-top"><span>确认撤回</span></div>
	    <div class="my-hint-body">
	      <div class="my-hint-text">
	        <span>确认撤回任务吗？</span>
	      </div>
	    </div>
	    <div class="my-hint-bottom">
	       <div class="block">
	         <p class="row">
	           <button class="col button button-big" id="cancel">取消</button>
	           <button class="col button button-big button-fill" id="confirm">确定</button>
	         </p>
		   </div>
	    </div>
	  </div>
	  `;
    openLayer(html, (el) => {
        jQuery("#cancel").off().click(function () {
            layer.closeAll();
        });

        jQuery("#confirm").off().click(function () {
            if (btnBack2) {
                layer.closeAll();
                btnBack2();
            }
        });
    });
}

/*安全指数*/
function getTextColorByScore(score, getRgba) {
    let fixScore = parseFloat(parseFloat(score).toFixed(1));
    if (79.9 < fixScore && fixScore < 89.9) { //风险
        return getRgba ? '#FFB32D' : "危险,需要及时整改"
    } else if (fixScore < 80) { //高危
        return getRgba ? '#FD5E5E' : "告急,需要立即处理"
    } else { //安全
        return getRgba ? '#47CFAD' : "安全,请继续保持"
    }
}

/*判断是不是浮点数*/
function isFloat(n) {
    return n + ".0" != n;
}

//字符串包含“天”就返回到天，否则原样返回
function isDay(remainTime) {
    if (!remainTime) {
        return "";
    }
    if (remainTime.substr(0, 2) == "0天") {
        return "剩余" + remainTime.substr(remainTime.lastIndexOf('天') + 1, remainTime.length) + "结束";
    } else {

        return "剩余" + remainTime.substr(0, remainTime.lastIndexOf('天') + 1) + "结束";
    }
}
//通过结束时间算出还剩多长时间
function toEndTime(endTime) {
    var times = endTime.replace(/-/g, '/');
    var dateTime = new Date(times).getTime() - new Date().getTime();
    //计算出相差天数
    var days = Math.floor(dateTime / (24 * 3600 * 1000))
    //计算出小时数
    var leave = dateTime % (24 * 3600 * 1000) //计算天数后剩余的毫秒数
    var hours = Math.floor(leave / (3600 * 1000))
    if (days > 0) {
        return "剩余" + days + "天结束";
    } else {
        return "剩余" + hours + "小时结束";
    }
}

/**
 * @Author: Chili
 * @Description: 展示图片,容器定宽高，图片自适应
 * position:1:接处警，设备物联 2:档案，高危信号，重点问题 3：维保相关  4：任务完成时间线  5：作业照片墙 6:隐患
 * @Date: 2019-07-15 16:34:40
 */
function showImage($el, picUrls, position) {
    if (position == 1 || position == 2) {
        if (picUrls) {
            $el.append(`
                <div class='image-item lazy lazy-fade-in' style='width:60px;height:60px;
                    background-position:center;
                    background-size:cover;
                    background-repeat:no-repeat;'
                    key-src="` + picUrls + `"
                    data-background="` + picUrls + `">
                </div>`);
            app.lazy.loadImage($el.find('.lazy'));
            $el.click(function (e) {
                let targetSrc = jQuery(e.target).attr("key-src");
                let targIndex = [picUrls].indexOf(targetSrc);
                openAndShowBigImage([picUrls], targIndex);
                //方法阻止事件冒泡到父元素，阻止任何父事件处理程序被执行。
                e.stopPropagation();
            });
        } else {
            if (position == 1) {
                $el.append(`<img src='` + staticPath + `img/default/defEqIcon.png' style='width:60px;height:60px;' />`);
            } else if (position == 2) {
                $el.append(`<img src='` + staticPath + `img/default/emptyUnit.png' style='width:60px;height:60px;' />`);
            }
        }
    } else {
        let srcArr = [];
        $el.empty().append(`<div class="link-image-groups"></div>`);
        if (picUrls) {
            if (picUrls.indexOf("data:image") > -1) {
                srcArr = picUrls.split(",data:image");
            } else {
                srcArr = picUrls.split(",");
            }
            if (position == 4) {
                for (let i = 0; i < srcArr.length; i++) {
                    if (srcArr[i] != "" && srcArr[i] != "null") {
                        if (srcArr[i].substr(srcArr[i].length - 3) === 'mp4' || srcArr[i].substr(srcArr[i].length - 3) === '3gp' || srcArr[i].substr(srcArr[i].length - 4) === 'mpeg' || srcArr[i].substr(srcArr[i].length - 6) === 'mavip4' || srcArr[i].substr(srcArr[i].length - 3) === 'flv' || srcArr[i].substr(srcArr[i].length - 3) === 'mov') {
                            $el.children().append(`
                                <div class='image-item lazy lazy-fade-in' style='
                                    background:url(` + staticPath + `img/common/video-detail.png` + `);
                                    background-position:center;
                                    background-size:cover;
                                    background-repeat:no-repeat;
                                    margin-bottom:3px;
                                    margin-right:7px;'
                                    key-src="` + srcArr[i] + `"
                                    data-background="` + staticPath + `img/common/video-detail.png` + `">
                                </div>`);
                        } else {
                            $el.children().append(`
                                <div class='image-item lazy lazy-fade-in' style='
                                    background:url(` + srcArr[i] + `);
                                    background-position:center;
                                    background-size:cover;
                                    background-repeat:no-repeat;
                                    margin-bottom:3px;
                                    margin-right:7px;'
                                    key-src="` + srcArr[i] + `"
                                    data-background="` + srcArr[i] + `">
                                </div>`);
                        }

                    }
                }
            } else if (position == 5) {
                for (let i = 0; i < srcArr.length; i++) {
                    if (srcArr[i] != "" && srcArr[i] != "null") {
                        if (srcArr[i].substr(srcArr[i].length - 3) === 'mp4' || srcArr[i].substr(srcArr[i].length - 3) === '3gp' || srcArr[i].substr(srcArr[i].length - 4) === 'mpeg' || srcArr[i].substr(srcArr[i].length - 6) === 'mavip4' || srcArr[i].substr(srcArr[i].length - 3) === 'flv' || srcArr[i].substr(srcArr[i].length - 3) === 'mov') {
                            $el.children().append(`<img src='` + staticPath + `img/common/video-detail.png' key-src="` + srcArr[i] + `" style='width:100px;height:100px;' />`);
                        } else {
                            $el.children().append(`
                                <div class='image-item lazy lazy-fade-in' style='
                                    background:url(` + srcArr[i] + `);
                                    background-position:center;
                                    background-size:cover;
                                    background-repeat:no-repeat;
                                    margin-right:4px;'
                                    key-src="` + srcArr[i] + `"
                                    data-background="` + srcArr[i] + `">
                                </div>`);
                        }

                    }
                }
            } else if (srcArr.length > 1 || position == 3) {
                for (let i = 0; i < srcArr.length; i++) {
                    var imgData = srcArr[i];
                    if (imgData.indexOf("base64,") > -1) {
                        if (imgData.indexOf("data:image") == -1) {
                            imgData = "data:image" + imgData;
                        }
                    }
                    if (srcArr[i].substr(srcArr[i].length - 3) === 'mp4' || srcArr[i].substr(srcArr[i].length - 3) === '3gp' || srcArr[i].substr(srcArr[i].length - 4) === 'mpeg' || srcArr[i].substr(srcArr[i].length - 6) === 'mavip4' || srcArr[i].substr(srcArr[i].length - 3) === 'flv' || srcArr[i].substr(srcArr[i].length - 3) === 'mov') {
                        $el.children().append(`<img src='` + staticPath + `img/common/video-detail.png' key-src="` + srcArr[i] + `" style='width:100px;height:100px;' />`);
                    } else {
                        $el.children().append(`
                            <div class='image-item lazy lazy-fade-in' style='
                                background:url(` + srcArr[i] + `);
                                background-position:center;
                                background-size:cover;
                                background-repeat:no-repeat;
                                margin-right:4px;'
                                key-src="` + srcArr[i] + `"
                                data-background="` + srcArr[i] + `">
                            </div>`);
                    }
                }
            } else {
                for (let i = 0; i < srcArr.length; i++) {
                    if (srcArr[i].substr(srcArr[i].length - 3) === 'mp4' || srcArr[i].substr(srcArr[i].length - 3) === '3gp' || srcArr[i].substr(srcArr[i].length - 4) === 'mpeg' || srcArr[i].substr(srcArr[i].length - 6) === 'mavip4' || srcArr[i].substr(srcArr[i].length - 3) === 'flv' || srcArr[i].substr(srcArr[i].length - 3) === 'mov') {
                        $el.children().append(`<img src='` + staticPath + `img/common/video_list.png' style='width:100%;height:150px;' key-src="` + srcArr[i] + `" />`)
                    } else {
                        $el.children().append(`
                            <div class='image-item lazy lazy-fade-in' style='width:100%;height:150px;
                                background:url(` + srcArr[i] + `);
                                background-position:center;
                                background-size:cover;
                                background-repeat:no-repeat;'
                                key-src="` + srcArr[i] + `"
                                data-background="` + srcArr[i] + `">
                            </div>`);
                    }
                }
            }
            app.lazy.create(".link-image-groups");
            $el.click(function (e) {
                let targetSrc = jQuery(e.target).attr("key-src");
                let targIndex = srcArr.indexOf(targetSrc);
                openAndShowBigImage(srcArr, targIndex);
                //方法阻止事件冒泡到父元素，阻止任何父事件处理程序被执行。
                e.stopPropagation();
            });
        } else {
            $el.append(`<img src='` + staticPath + `img/emptyImg/bynone.png' style='margin-left: calc(50% - 140px);' />`);
        }
    }
}

/**
 * @Author: Chili
 * @Description: 图片视频展开查看事件
 * @Date: 2019-07-15 17:01:15
 */
let linkPhotoBrowser = null;

function openAndShowBigImage(srcArr, index) {
    let arr = []
    for (let i = 0; i < srcArr.length; i++) {
        if (srcArr[i].toString().substring(srcArr[i].length - 3) === 'mp4' || srcArr[i].toString().substring(srcArr[i].length - 3) === '3gp' || srcArr[i].toString().substring(srcArr[i].length - 4) === 'mpeg' || srcArr[i].toString().substring(srcArr[i].length - 6) === 'mavip4' || srcArr[i].toString().substring(srcArr[i].length - 3) === 'flv' || srcArr[i].toString().substring(srcArr[i].length - 3) === 'mov') {
            arr.push({
                html: '<video src="' + srcArr[i] + '" style="width:100%;" controls="controls" webkit-playsinline playsinline></video>',
            })
        } else {
            arr.push(srcArr[i])
        }
    }
    linkPhotoBrowser = app.photoBrowser.create({
        photos: arr,
        type: 'standalone',
        routableModals: false,
        backLinkText: 'Back',
        theme: 'dark',
        expositionHideCaptions: true,
        swipeToClose: true,
        toolbar: false,
        // allowsInlineMediaPlayback:true
    });
    // if(srcArr[index].substr(srcArr[index].length - 3) === 'mp4' || srcArr[index].substr(srcArr[index].length - 3) === '3gp' || srcArr[index].substr(srcArr[index].length - 4) === 'mpeg' || srcArr[index].substr(srcArr[index].length - 6) === 'mavip4' || srcArr[index].substr(srcArr[index].length - 3) === 'flv' || srcArr[index].substr(srcArr[index].length - 3) === 'mov'){
    //     linkPhotoBrowser = app.photoBrowser.create({
    //         photos : [
    //             {
    //                 html: '<video src="'+srcArr[index]+'" style="width:100%;" autoplay="autoplay"></video>',
    //             }
    //         ],
    //         theme: 'dark',
    //         type: 'standalone'
    //     });
    // }else{
    //     linkPhotoBrowser = app.photoBrowser.create({
    //         photos: srcArr,
    //         type: 'standalone',
    //         routableModals: false,
    //         backLinkText: 'Back',
    //         theme: 'dark',
    //         expositionHideCaptions: true,
    //         swipeToClose: true,
    //         toolbar: false,
    //     });
    // }
    linkPhotoBrowser.open(index);
}

/**
 * @Author: Chili
 * @Description: 语音播报
 * @Date: 2019-08-01 14:26:45
 */
function showVoiceBtn(el, length, voice) {
    if (voice && length > 0) {
        let voiceHtml = `<div class="ilink-voice-on">
            <img src="` + staticPath + `img/apply/voicePlay.png" /><span>语音播放</span>
            <audio preload="auto" hidden="true" data-play="0">
                <source src="` + voice + `" type="audio/mpeg">
            </audio>
        </div>`;
        jQuery(el).html(voiceHtml);
        jQuery(el).click(function (e) {
            // //先看页面有没有其他语音并停止
            // if(jQuery("audio").length >0){
            //     jQuery.each(jQuery("audio"),function(index,val){
            //         val.pause();
            //         val.currentTime = 0;
            //     });
            // }
            let vo = jQuery(e.currentTarget).find("audio");
            if (jQuery(vo).attr("data-play") == "0") {
                vo[0].play();
                jQuery(vo).parent().find("img")[0].src = staticPath + "img/apply/voicePlay.gif";
                jQuery(vo).parent().find("span").html("正在播放...").css("color", "#2471CA");
                jQuery(vo).parent().css("color", "#2471CA");
                jQuery(vo).attr("data-play", "1");
            } else {
                // vo[0].currentTime = 0;
                vo[0].pause();
                jQuery(vo).parent().find("img")[0].src = staticPath + "img/apply/voicePlay.png";
                jQuery(vo).parent().find("span").html("语音播放").css("color", "#999");
                jQuery(vo).parent().css("color", "#999");
                jQuery(vo).attr("data-play", "0");
            }
            vo[0].addEventListener('ended', function () {
                vo[0].pause();
                vo[0].currentTime = 0;
                jQuery(vo).parent().find("img")[0].src = staticPath + "img/apply/voicePlay.png";
                jQuery(vo).parent().find("span").html("语音播放").css("color", "#999");
                jQuery(vo).parent().css("color", "#999");
                jQuery(vo).attr("data-play", "0");
            }, false);

            e.stopPropagation();
        });
    }
}

/**
 * @Author : hiny
 * @Description : 记录用户登录时间
 * @param {flag} 0:回到app 1:进入后台 2:杀死app
 * @Date : 2019-10-14 15:34:10
 */
let userStartTime = null;

function uploadUserTime(flag) {
    if (flag == 0) {
        userStartTime = moment().format("YYYY-MM-DD HH:mm:ss");
        return;
    }
    if (!userStartTime || !userInfor || !userInfor.accountName || !userInfor.organizationIds) {
        return;
    }
    var userEndTime = moment().format("YYYY-MM-DD HH:mm:ss");
    var time = {
        materialsId: 0,
        learningAccount: userInfor.accountName,
        learningStartTime: userStartTime,
        learningEndTime: userEndTime,
        orgId: userInfor.org.id
    }
    Dao.saveLearningTime({
        timeList: JSON.stringify([time])
    }, function (data) {});
}